'use strict';
const path = require('path');
const defaultSettings = require('./src/settings.js');
const { index, login, callback, game, mobile, league, mbleague, print, train, shoppingmall, hall, mycenter, integral } = require('./pages');
const chalk = require('chalk');

const fromConsole = chalk.bold.blue;
const jsConsole = chalk.bold.yellow;
const cssConsole = chalk.keyword('orange');
process.env.VUE_APP_JSONVERSION = new Date().getTime();

function resolve (dir) {
  return path.join(__dirname, dir);
}

let pages = {}; // 多页面入口
let defaultPage; // 忽略入口
switch (process.env.VUE_APP_DIREVTOR) {
  case 'login':
    pages = { login, callback };
    defaultPage = [index, game, mobile, league, mbleague, print, train, shoppingmall, hall, mycenter, integral];
    break;
  case 'dev':
    pages = { login, callback, index, game, mobile, league, mbleague, print, train, shoppingmall, hall, mycenter, integral };
    defaultPage = [];
    break;
  case 'version':
    pages = { index, callback, game, mobile, league, mbleague, print, train, shoppingmall, hall, mycenter, integral };
    defaultPage = [login];
    break;
  default:
    pages = { index, callback, game, mobile, league, mbleague, print, train, shoppingmall, hall, mycenter, integral };
    defaultPage = [login];
}
const name = defaultSettings.title || '跆拳道大满贯数字化管理平台'; // page title

const port = process.env.port || process.env.npm_config_port || process.env.VUE_APP_PORT || 9003;// dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  publicPath: '/',
  outputDir: process.env.VUE_APP_OUTDIR_URL ? process.env.VUE_APP_OUTDIR_URL : 'dist',
  assetsDir: 'web_static',
  indexPath: './index.html',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: process.env.NODE_ENV === 'development',
  pages: pages,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    before: require('./mock/mock-server.js'),
    proxy: {
      '/dev-api/api/*': {
        target: process.env.VUE_APP_API_SWAGGER + '/api',
        secure: false,
        pathRewrite: {
          '^/dev-api/api': ''
        }
      }
    }
  },
  css: {
    extract: false
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    devtool: 'source-map',
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  chainWebpack (config) {
    // // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch');
    config.plugins.delete('preload');

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              // inline: /runtime\..*\.js$/
            }])
            .end();
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            });
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single');
          // 去除console.log
          if (process.env.VUE_APP_REMOVE_CONSOLELOG === 'true') {
            config.optimization
              .minimizer('terser')
              .tap(args => {
                Object.assign(args[0].terserOptions.compress, { // 生产模式 console.log 去除
                  // warnings: false , // 默认 false
                  // drop_console:  ,
                  // drop_debugger: true, // 默认也是true
                  pure_funcs: ['console.log']
                });
                return args;
              });
          }
        }
      );

    if (process.env.use_analyzer) {
      config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);
    }
    let _tip = '';
    if (process.env.VUE_APP_DIREVTOR !== 'dev') {
      _tip = jsConsole(`********************************************
      ${fromConsole(process.env.VUE_APP_BUILD_TIP)}
      打包的文件夹：${cssConsole(process.env.VUE_APP_OUTDIR_URL)}
********************************************`);
    }
    config.plugin('Plusgstest').use(require('./plugins/test'), [{ pages: defaultPage, tip: _tip }]);
  }
};
